//
//  CNetWorkRequest.m
//  Delicious
//
//  Created by apple on 11-11-8.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CNetWorkRequest.h"

@implementation CNetWorkRequest


@synthesize m_Delegate;
@synthesize m_UrlRequest;
@synthesize m_UrlConnection;
@synthesize m_Data;
@synthesize m_bIsLoaded;
@synthesize m_TimeOutTimer;

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
        
        m_UrlConnection = nil;
        m_UrlRequest    = nil;
        m_Delegate      = nil;
        m_bIsLoaded     = NO;
        m_Data          = nil;
    }
    
    return self;
}

-(void)dealloc
{
    [m_UrlRequest release];
    [m_UrlConnection release];
    [m_Data release];
    [m_TimeOutTimer invalidate];
    m_TimeOutTimer = nil;
    
    [super dealloc];
}

-(void)Stop
{
    m_bIsLoaded = YES;
    [m_UrlConnection cancel];
    [m_UrlConnection release];
    m_UrlConnection = nil;
    [m_UrlRequest release];
    m_UrlRequest = nil;
    [m_Data release];
    m_Data = nil;
    
    [m_TimeOutTimer invalidate];
    m_TimeOutTimer = nil;
    
    m_Delegate = nil;
}

-(void)SetRequestWithUrl:(NSString*)url Method:(MethodType)type Value:(NSData*)data IsSynchronous:(BOOL)issynchronous OutTime:(int)outtime
{
    if (!m_bIsLoaded)
    {
        m_bIsLoaded = YES;
        [m_UrlRequest release];
        m_UrlRequest = nil;
        [m_UrlConnection release];
        m_UrlConnection = nil;
        [m_Data release];
        m_Data = nil;
        
        //网络状态
        if ([AppConfig DefaultAppConfig].m_bIsNetWork)
        {
            //NSLog(@"\r\n\r\n<--------请求服务器(%@)-------->\r\n\r\n", url);
            NSURL *Url = [NSURL URLWithString:url];

            //body
            if (nil == m_Data)
            {
                m_Data = [NSMutableData data];
                [m_Data retain];
            }
            
            //同步
            if (issynchronous)
            {
                //
            }
            //异步
            else 
            {
                m_UrlRequest = [[NSMutableURLRequest alloc] initWithURL:Url];
                
                //get
                if (Get == type)
                {
                    [m_UrlRequest setHTTPMethod:@"GET"];
                }
                //post
                else if (Post == type)
                {
                    [m_UrlRequest setHTTPMethod:@"POST"];
                    
                    if (nil != data)
                    {
                        [m_UrlRequest setHTTPBody:data];
                    }
                }
                //postimage
                else if (PostImage == type)
                {
                    [m_UrlRequest setHTTPMethod:@"POST"];
                    [m_UrlRequest setValue:MULTIPART forHTTPHeaderField:@"Content-Type"];
                    
                    if (nil != data)
                    {
                        NSMutableData *body = [NSMutableData data];
                        [body appendData:[HEADER dataUsingEncoding:NSUTF8StringEncoding]];
                        [body appendData:[[NSString stringWithString:IMAGE_CONTNET] dataUsingEncoding:NSUTF8StringEncoding]];
                        [body appendData:[CONTENTTYPE dataUsingEncoding:NSUTF8StringEncoding]];
                        [body appendData:data];
                        [body appendData:[END dataUsingEncoding:NSUTF8StringEncoding]];
                        
                        [m_UrlRequest setHTTPBody:body];
                    }
                }
                else {;}
                
                m_UrlConnection = [[NSURLConnection alloc] initWithRequest:m_UrlRequest delegate:self];
                [m_UrlConnection start];
                
                //请求超时处理
                m_TimeOutTimer = [NSTimer scheduledTimerWithTimeInterval:outtime target:self selector:@selector(RequestTimeout:) userInfo:nil repeats:NO];
            }
        }
        else 
        {        
            [self RequestNoNetWork];
        }
    }
}

-(void)RequestTimeout:(NSTimer*)timer
{
    //NSLog(@"\r\n\r\nNSURLConnection连接超时\r\n\r\n");
    m_bIsLoaded = NO;
    
    [m_TimeOutTimer isValid];
    m_TimeOutTimer = nil;
    [m_UrlConnection cancel];
    
    [m_UrlRequest release];
    m_UrlRequest = nil;
    [m_UrlConnection release];
    m_UrlConnection = nil;
    [m_Data release];
    m_Data = nil;
    
    [m_Delegate DidRectiveTimeout:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    /*//NSLog(@"<--------didReceiveResponse(Start：%@)-------->", response.URL);
    
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;

    NSDictionary *dictionary = [httpResponse allHeaderFields];
    //NSLog(@"%@",[dictionary description]);
    //NSLog(@"%d(%@)", [httpResponse statusCode], [NSHTTPURLResponse localizedStringForStatusCode:[httpResponse statusCode]]);
    
    //NSLog(@"<--------didReceiveResponse(End)-------->");*/
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [m_Data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{   
    //NSLog(@"\r\n\r\nNSURLConnection连接完成\r\n\r\n");
    m_bIsLoaded = NO;
    
    [m_TimeOutTimer invalidate];
    m_TimeOutTimer = nil;
    [m_UrlRequest release];
    m_UrlRequest = nil;
    [m_UrlConnection release];
    m_UrlConnection = nil;
    
    [m_Delegate DidReceiveData:self Data:m_Data];
    
    [m_Data release];
    m_Data = nil;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{    
    //NSLog(@"\r\n\r\nNSURLConnection连接错误\r\n\r\n");
    m_bIsLoaded = NO;
    
    [m_TimeOutTimer invalidate];
    m_TimeOutTimer = nil;
    [m_UrlRequest release];
    m_UrlRequest = nil;
    [m_UrlConnection release];
    m_UrlConnection = nil;
    [m_Data release];
    m_Data = nil;
    
    [m_Delegate DidReceiveError:self Error:error];
}

-(void)RequestNoNetWork
{
    //NSLog(@"\r\n\r\nNSURLConnection连接失败,没有网络\r\n\r\n");
    m_bIsLoaded = NO;
    
    [m_TimeOutTimer invalidate];
    m_TimeOutTimer = nil;
    [m_Delegate DidStopRequestNoNet:self];
}

@end
